# Copyright (c) 2009 Barry Schwartz
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

#--------------------------------------------------------------------------
import os
from os import access, symlink, walk, F_OK
from os.path import abspath, dirname, join, relpath
from SCons.Action import ActionFactory
from SCons.Defaults import Mkdir, Copy

#--------------------------------------------------------------------------

def make_build_tree_dir(env, build_dir, rel_dir):
    if not access(build_dir, F_OK):
        env.Execute(Mkdir(build_dir))
    bdir = join(build_dir, rel_dir)
    if not access(bdir, F_OK):
        env.Execute(Mkdir(bdir))


def make_build_tree_file(env, build_dir, rel_dir, file_name):

    env = env.Clone()

    Symlink = ActionFactory((lambda dest, src: symlink(relpath(src, dirname(dest)), dest)),
                            (lambda dest, src: 'Symlink("%s", "%s")' % (dest, src)),
                            convert=str)

    # Skip Emacs backup files, and files created by 'patch'.
    if (file_name[-1:] != '~' and
        file_name[:1]  != '#' and
        file_name[:2]  != '.#' and
        file_name[-4:] != '.rej' and
        file_name[-5:] != '.orig'):
        source = abspath(join(rel_dir, file_name))
        dest_dir = join(build_dir, rel_dir)
        if 'symlink' in dir(os):
            destination = join(dest_dir, file_name)        
            if not access(destination, F_OK):
                env.Execute(Symlink(destination, source))
        else:
            env.Execute(Copy(dest_dir, source))


def make_build_tree(env, src_dir, build_dir):

    for (dirpath, dirnames, filenames) in walk(src_dir):
        rel_dir = relpath(dirpath)
        make_build_tree_dir(env, build_dir, rel_dir)
        for file_name in filenames:
            make_build_tree_file(env, build_dir, rel_dir, file_name)

#--------------------------------------------------------------------------
